<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <div class="header">
        <h2 class="page-title">来访登记管理</h2> <!-- 修改标题 -->
        <el-button type="primary" icon="el-icon-plus" @click="addRegistration">新增登记</el-button>
      </div>

      <!-- 来访申请审批模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover" class="card">
            <div slot="header" class="clearfix">
              <span class="module-title">来访申请审批</span>
            </div>
            <el-table :data="pendingApprovals" style="width: 100%" border stripe>
              <el-table-column prop="registrationNumber" label="登记编号" width="150"></el-table-column>
              <el-table-column prop="elderlyName" label="老人姓名" width="150"></el-table-column>
              <el-table-column prop="visitDate" label="来访日期" width="150"></el-table-column>
              <el-table-column prop="visitReason" label="来访原因" width="200"></el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button type="text" @click="approve(scope.row)">批准</el-button>
                  <el-button type="text" @click="reject(scope.row)">拒绝</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- 来访历史记录模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover" class="card">
            <div slot="header" class="clearfix">
              <span class="module-title">来访历史记录</span>
              <el-button type="primary" icon="el-icon-plus" @click="addHistory" style="float: right;">新增记录</el-button>
            </div>
            <ul class="history-list">
              <li v-for="(history, index) in outingHistory" :key="index">
                {{ history.date }}: {{ history.elderlyName }} 来访，原因: {{ history.reason }}
                <el-button type="text" @click="editHistory(history)">编辑</el-button>
                <el-button type="text" @click="deleteHistory(history)" class="delete-btn">删除</el-button>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <!-- 来访安全提示模块 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="24">
          <el-card shadow="hover" class="card">
            <div slot="header" class="clearfix">
              <span class="module-title">来访安全提示</span>
              <el-button type="primary" icon="el-icon-plus" @click="addTip" style="float: right;">新增提示</el-button>
            </div>
            <ul class="safety-tips">
              <li v-for="(tip, index) in safetyTips" :key="index">
                <i class="el-icon-info safety-icon"></i>
                {{ tip.tip }}
                <el-button type="text" @click="editTip(tip)">编辑</el-button>
                <el-button type="text" @click="deleteTip(tip)" class="delete-btn">删除</el-button>
              </li>
            </ul>
          </el-card>
        </el-col>
      </el-row>

      <!-- 新增/编辑登记对话框 -->
      <el-dialog :title="registrationDialogTitle" :visible.sync="registrationDialogVisible">
        <el-form :model="registrationForm" label-width="120px">
          <el-form-item label="登记编号">
            <el-input v-model="registrationForm.registrationNumber"></el-input>
          </el-form-item>
          <el-form-item label="老人姓名">
            <el-input v-model="registrationForm.elderlyName"></el-input>
          </el-form-item>
          <el-form-item label="来访日期">
            <el-date-picker v-model="registrationForm.visitDate" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="来访原因">
            <el-input v-model="registrationForm.visitReason"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="registrationDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRegistration">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑历史记录对话框 -->
      <el-dialog :title="historyDialogTitle" :visible.sync="historyDialogVisible">
        <el-form :model="historyForm" label-width="120px">
          <el-form-item label="日期">
            <el-date-picker v-model="historyForm.date" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="老人姓名">
            <el-input v-model="historyForm.elderlyName"></el-input>
          </el-form-item>
          <el-form-item label="来访原因">
            <el-input v-model="historyForm.reason"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="historyDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitHistory">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增/编辑安全提示对话框 -->
      <el-dialog :title="tipDialogTitle" :visible.sync="tipDialogVisible">
        <el-form :model="tipForm" label-width="120px">
          <el-form-item label="提示内容">
            <el-input v-model="tipForm.tip"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="tipDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitTip">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import axios from 'axios'

export default {
  name: 'OutingRegistration',
  components: {
    AsideLayout
  },
  data() {
    return {
      pendingApprovals: [],
      outingHistory: [],
      safetyTips: [],
      registrationDialogVisible: false,
      registrationDialogTitle: '',
      registrationForm: {
        id: null,
        registrationNumber: '',
        elderlyName: '',
        visitDate: '',
        visitReason: '',
        status: 'pending'
      },
      historyDialogVisible: false,
      historyDialogTitle: '',
      historyForm: {
        id: null,
        date: '',
        elderlyName: '',
        reason: ''
      },
      tipDialogVisible: false,
      tipDialogTitle: '',
      tipForm: {
        id: null,
        tip: ''
      }
    };
  },
  mounted() {
    this.fetchPendingApprovals();
    this.fetchOutingHistory();
    this.fetchSafetyTips();
  },
  methods: {
    fetchPendingApprovals() {
      axios.get('http://localhost:3000/api/outing-registrations_vistor')
        .then(response => {
          this.pendingApprovals = response.data;
        })
        .catch(error => {
          console.error('Error fetching pending approvals:', error);
        });
    },
    fetchOutingHistory() {
      axios.get('http://localhost:3000/api/outing-history_vistor')
        .then(response => {
          this.outingHistory = response.data;
        })
        .catch(error => {
          console.error('Error fetching outing history:', error);
        });
    },
    fetchSafetyTips() {
      axios.get('http://localhost:3000/api/safety-tips_vistor')
        .then(response => {
          this.safetyTips = response.data;
        })
        .catch(error => {
          console.error('Error fetching safety tips:', error);
        });
    },
    addRegistration() {
      this.registrationDialogTitle = '新增登记';
      this.registrationForm = {
        id: null,
        registrationNumber: '',
        elderlyName: '',
        visitDate: '',
        visitReason: '',
        status: 'pending'
      };
      this.registrationDialogVisible = true;
    },
    editRegistration(row) {
      this.registrationDialogTitle = '编辑登记';
      this.registrationForm = { ...row };
      this.registrationDialogVisible = true;
    },
    submitRegistration() {
      if (this.registrationForm.id) {
        axios.put(`http://localhost:3000/api/outing-registrations_vistor/${this.registrationForm.id}`, this.registrationForm)
          .then(() => {
            this.fetchPendingApprovals();
            this.registrationDialogVisible = false;
            this.$message.success('更新登记成功');
          })
          .catch(error => {
            console.error('Error updating registration:', error);
            this.$message.error('更新登记失败');
          });
      } else {
        axios.post('http://localhost:3000/api/outing-registrations_vistor', this.registrationForm)
          .then(() => {
            this.fetchPendingApprovals();
            this.registrationDialogVisible = false;
            this.$message.success('新增登记成功');
          })
          .catch(error => {
            console.error('Error adding registration:', error);
            this.$message.error('新增登记失败');
          });
      }
    },
    approve(row) {
      axios.put(`http://localhost:3000/api/outing-registrations_vistor/${row.id}`, { status: 'approved' })
        .then(() => {
          this.fetchPendingApprovals();
          this.$message.success('批准成功');
        })
        .catch(error => {
          console.error('Error approving registration:', error);
          this.$message.error('批准失败');
        });
    },
    reject(row) {
      axios.put(`http://localhost:3000/api/outing-registrations_vistor/${row.id}`, { status: 'rejected' })
        .then(() => {
          this.fetchPendingApprovals();
          this.$message.success('拒绝成功');
        })
        .catch(error => {
          console.error('Error rejecting registration:', error);
          this.$message.error('拒绝失败');
        });
    },
    addHistory() {
      this.historyDialogTitle = '新增记录';
      this.historyForm = {
        id: null,
        date: '',
        elderlyName: '',
        reason: ''
      };
      this.historyDialogVisible = true;
    },
    editHistory(row) {
      this.historyDialogTitle = '编辑记录';
      this.historyForm = { ...row };
      this.historyDialogVisible = true;
    },
    submitHistory() {
      if (this.historyForm.id) {
        axios.put(`http://localhost:3000/api/outing-history_vistor/${this.historyForm.id}`, this.historyForm)
          .then(() => {
            this.fetchOutingHistory();
            this.historyDialogVisible = false;
            this.$message.success('更新记录成功');
          })
          .catch(error => {
            console.error('Error updating history:', error);
            this.$message.error('更新记录失败');
          });
      } else {
        axios.post('http://localhost:3000/api/outing-history_vistor', this.historyForm)
          .then(() => {
            this.fetchOutingHistory();
            this.historyDialogVisible = false;
            this.$message.success('新增记录成功');
          })
          .catch(error => {
            console.error('Error adding history:', error);
            this.$message.error('新增记录失败');
          });
      }
    },
    deleteHistory(row) {
      this.$confirm(`确认删除记录 ${row.date}: ${row.elderlyName} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/outing-history_vistor/${row.id}`)
          .then(() => {
            this.fetchOutingHistory();
            this.$message.success('删除成功');
          })
          .catch(error => {
            console.error('Error deleting history:', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    addTip() {
      this.tipDialogTitle = '新增提示';
      this.tipForm = {
        id: null,
        tip: ''
      };
      this.tipDialogVisible = true;
    },
    editTip(row) {
      this.tipDialogTitle = '编辑提示';
      this.tipForm = { ...row };
      this.tipDialogVisible = true;
    },
    submitTip() {
      if (this.tipForm.id) {
        axios.put(`http://localhost:3000/api/safety-tips_vistor/${this.tipForm.id}`, this.tipForm)
          .then(() => {
            this.fetchSafetyTips();
            this.tipDialogVisible = false;
            this.$message.success('更新提示成功');
          })
          .catch(error => {
            console.error('Error updating tip:', error);
            this.$message.error('更新提示失败');
          });
      } else {
        axios.post('http://localhost:3000/api/safety-tips_vistor', this.tipForm)
          .then(() => {
            this.fetchSafetyTips();
            this.tipDialogVisible = false;
            this.$message.success('新增提示成功');
          })
          .catch(error => {
            console.error('Error adding tip:', error);
            this.$message.error('新增提示失败');
          });
      }
    },
    deleteTip(row) {
      this.$confirm(`确认删除提示 ${row.tip} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/safety-tips_vistor/${row.id}`)
          .then(() => {
            this.fetchSafetyTips();
            this.$message.success('删除成功');
          })
          .catch(error => {
            console.error('Error deleting tip:', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<style scoped>
.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.card {
  border-radius: 10px;
  overflow: hidden;
}

.module-title {
  font-size: 18px;
  font-weight: 600;
  color: #555;
}

.history-list, .safety-tips {
  padding: 10px;
  list-style-type: none;
}

.history-list li, .safety-tips li {
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.safety-icon {
  margin-right: 8px;
  color: #f56c6c; /* 红色图标 */
}

.el-container {
  height: 100vh; /* 使容器高度适应视口 */
}

.el-main {
  padding: 20px;
  overflow-y: auto; /* 允许垂直滚动 */
  display: flex;
  flex-direction: column; /* 使内容垂直排列 */
}

/* 使导航栏和页面适应全局 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  width: 100%; /* 使标题适应全宽 */
}

/* 使页面内容适应全宽 */
.statistics-card, .reminder-list {
  width: 100%; /* 使卡片和列表适应全宽 */
}
</style>